import React, { useState, useEffect } from "react";
import {
  Card,
  Table,
  Space,
  Button,
  Tag,
  Modal,
  message,
  Input,
  Select,
  DatePicker,
  Typography,
} from "antd";
import {
  DeleteOutlined,
  ExclamationCircleOutlined,
  UserOutlined,
  MessageOutlined,
  LikeOutlined,
  EyeOutlined,
} from "@ant-design/icons";
import type { DiscussionPost } from "../../../types/discussion";
import { useUser } from "../../../contexts/UserContext";
import PermissionGuard from "../../../components/PermissionGuard";

const { Title } = Typography;
const { Search } = Input;
const { RangePicker } = DatePicker;
const { confirm } = Modal;

interface DiscussionFilter {
  keyword?: string;
  sortBy: "latest" | "popular" | "mostReplies";
  timeRange?: [string, string];
}

const DiscussionManagement: React.FC = () => {
  const { user } = useUser();
  const [loading, setLoading] = useState(false);
  const [discussions, setDiscussions] = useState<DiscussionPost[]>([]);
  const [filter, setFilter] = useState<DiscussionFilter>({
    sortBy: "latest",
  });
  const [selectedRows, setSelectedRows] = useState<string[]>([]);

  useEffect(() => {
    loadDiscussions();
  }, [filter]);

  const loadDiscussions = async () => {
    setLoading(true);
    try {
      // TODO: 调用API获取讨论列表
      setLoading(false);
    } catch (error) {
      message.error("加载讨论列表失败");
      setLoading(false);
    }
  };

  const handleSearch = (value: string) => {
    setFilter({ ...filter, keyword: value });
  };

  const handleSortChange = (value: "latest" | "popular" | "mostReplies") => {
    setFilter({ ...filter, sortBy: value });
  };

  const handleDateRangeChange = (dates: any) => {
    if (dates) {
      setFilter({
        ...filter,
        timeRange: dates.map((date: any) => date.format("YYYY-MM-DD")),
      });
    } else {
      setFilter({ ...filter, timeRange: undefined });
    }
  };

  const handleDelete = (ids: string[]) => {
    confirm({
      title: "确认删除",
      icon: <ExclamationCircleOutlined />,
      content: `确定要删除选中的 ${ids.length} 条讨论吗？此操作不可恢复。`,
      onOk: async () => {
        try {
          // TODO: 调用删除API
          message.success("删除成功");
          loadDiscussions();
          setSelectedRows([]);
        } catch (error) {
          message.error("删除失败，请重试");
        }
      },
    });
  };

  const columns = [
    {
      title: "标题",
      dataIndex: "title",
      key: "title",
      render: (text: string, record: DiscussionPost) => (
        <Space>
          <a href={`/discussion/${record.id}`}>{text}</a>
          {record.aiResponse && <Tag color="purple">AI已回复</Tag>}
        </Space>
      ),
    },
    {
      title: "作者",
      dataIndex: ["author", "name"],
      key: "author",
      render: (text: string, record: DiscussionPost) => (
        <Space>
          <UserOutlined />
          {text}
          <Tag color={record.author.role === "teacher" ? "blue" : undefined}>
            {record.author.role === "teacher" ? "教师" : "学生"}
          </Tag>
        </Space>
      ),
    },
    {
      title: "课程",
      dataIndex: ["course", "name"],
      key: "course",
    },
    {
      title: "标签",
      dataIndex: "tags",
      key: "tags",
      render: (tags: string[]) => (
        <Space>{tags?.map((tag) => <Tag key={tag}>{tag}</Tag>)}</Space>
      ),
    },
    {
      title: "统计",
      key: "stats",
      render: (_: any, record: DiscussionPost) => (
        <Space>
          <span>
            <EyeOutlined /> {record.views}
          </span>
          <span>
            <LikeOutlined /> {record.likes}
          </span>
          <span>
            <MessageOutlined /> {record.replies?.length || 0}
          </span>
        </Space>
      ),
    },
    {
      title: "发布时间",
      dataIndex: "createTime",
      key: "createTime",
      sorter: (a: DiscussionPost, b: DiscussionPost) =>
        new Date(a.createTime).getTime() - new Date(b.createTime).getTime(),
    },
    {
      title: "操作",
      key: "action",
      render: (_: any, record: DiscussionPost) => (
        <Space>
          <Button
            type="text"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete([record.id])}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <PermissionGuard permission="discussion.manage">
      <div style={{ padding: "24px" }}>
        <Card>
          <Space direction="vertical" style={{ width: "100%" }}>
            <Space style={{ marginBottom: 16 }}>
              <Title level={4} style={{ margin: 0 }}>
                讨论管理
              </Title>
            </Space>

            <Space style={{ marginBottom: 16 }}>
              <Search
                placeholder="搜索讨论..."
                onSearch={handleSearch}
                style={{ width: 300 }}
              />
              <Select
                value={filter.sortBy}
                onChange={handleSortChange}
                style={{ width: 120 }}
                options={[
                  { label: "最新", value: "latest" },
                  { label: "最热", value: "popular" },
                  { label: "最多回复", value: "mostReplies" },
                ]}
              />
              <RangePicker onChange={handleDateRangeChange} />
              <Button
                type="primary"
                danger
                icon={<DeleteOutlined />}
                disabled={selectedRows.length === 0}
                onClick={() => handleDelete(selectedRows)}
              >
                批量删除
              </Button>
            </Space>

            <Table
              rowKey="id"
              columns={columns}
              dataSource={discussions}
              loading={loading}
              rowSelection={{
                selectedRowKeys: selectedRows,
                onChange: (selectedRowKeys) =>
                  setSelectedRows(selectedRowKeys as string[]),
              }}
              pagination={{
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total) => `共 ${total} 条讨论`,
              }}
            />
          </Space>
        </Card>
      </div>
    </PermissionGuard>
  );
};

export default DiscussionManagement;
